Imports System.Runtime.InteropServices
Imports System.Text

Namespace Framework

    ''' <summary>
    ''' Activates the existing window by its title.
    ''' </summary>
    Public NotInheritable Class WindowsActivator
        Private Const SW_SHOWNOACTIVATE As Integer = 4

#Region " Win32 Imports "
        Private Delegate Function EnumWindowProc(ByVal handle As IntPtr, ByVal lParam As Integer) As Boolean


        <DllImport("user32.dll")> _
        Private Shared Function SetForegroundWindow(ByVal handle As IntPtr) As Integer
        End Function


        <DllImport("user32.dll")> _
        Private Shared Function ShowWindow(ByVal handle As IntPtr, ByVal cmdShow As Integer) As Boolean
        End Function


        <DllImport("user32.dll")> _
        Private Shared Function EnumWindows(ByVal ewp As EnumWindowProc, ByVal lParam As Integer) As Boolean
        End Function

        <DllImport("user32.dll")> _
        Private Shared Function GetWindowText(ByVal handle As IntPtr, ByVal sb As StringBuilder, ByVal maxCount As Integer) As Integer
        End Function
#End Region

        Private Sub New()
        End Sub

        Public Shared Sub ActivateWindow(ByVal wndName As String)
            mWndName = wndName
            Try
                Dim ewp As EnumWindowProc = New EnumWindowProc(AddressOf WindowEnumerated)
                EnumWindows(ewp, 0)
                GC.KeepAlive(ewp)
            Finally
                mWndName = Nothing
            End Try
        End Sub

        Private Shared Function WindowEnumerated(ByVal handle As IntPtr, ByVal lParam As Integer) As Boolean
            Const bufSize As Integer = 1000

            Dim sb As StringBuilder = New StringBuilder(bufSize)

            GetWindowText(handle, sb, bufSize - 1)
            If sb.ToString().StartsWith(mWndName) Then
                SetForegroundWindow(handle)
                ShowWindow(handle, SW_SHOWNOACTIVATE)
                Return False
            End If
            Return True
        End Function

        Private Shared mWndName As String
    End Class
End Namespace

